package com.pdg.mcplugin.ih;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Logger;

public class DataProvider {

	//plugin
	private InvisibleHand plugin;
	public InvisibleHand getPlugin(){
		return plugin;
	}

	//logger
	public Logger getLogger(){
		return getPlugin().getLogger();
	}
	
	private void ensureDataFolder(){
		File folder = getPlugin().getDataFolder();
		if(!folder.exists()){
			if(folder.mkdir()){
				getLogger().info(Constants.messageCreatedDataFolder);
			}else{
				getLogger().severe(Constants.errorCouldNotCreateDataFolder);
			}
		}
	}
	
	//connection
	private Connection connection;
	public Connection getConnection(){
		if(connection==null){
			ensureDataFolder();
			try{
				Class.forName(Constants.classNameSQLite);
			} catch(Exception e){
				getLogger().info(Constants.errorCouldNotLoadSQLite);
				e.printStackTrace();
				return null;
			}
			try{
				connection = DriverManager.getConnection(String.format(Constants.connectionString,getPlugin().getDataFolder().toString()));
			}catch(Exception e){
				getLogger().info(Constants.errorCouldNotConnectToDatabase);
				e.printStackTrace();
				connection = null;
				return null;
			}
		}
		return connection;
	}
	
	public DataProvider(InvisibleHand thePlugin){
		plugin = thePlugin;
	}
}
